package com.wangsd.web.controller;

import com.wangsd.web.entity.User;
import com.wangsd.web.service.UserService;
import com.wangsd.web.utils.ErrorTips;
import com.wangsd.web.utils.R;
import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@RestController
@RequestMapping("/user")
@Api(tags = "用户接口")
public class UserController {

    @Resource
    private UserService userService;


    /**
     * 用户登录
     * @param username 用户名
     * @param password 密码
     * @param request 请求对象
     * @return 登录信息
     */
    @PostMapping("/login")
    @ApiOperation("用户登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名"),
            @ApiImplicitParam(name = "password", value = "密码")
    })
    public R login(
            @RequestParam(name = "username", defaultValue = "guest", required = true) String username,
            @RequestParam(name = "password", defaultValue = "guest") String password,
            HttpServletRequest request,
            HttpServletResponse response) {

        User user = this.userVerify(username);
        // 用户合法性验证
        if (user == null) {
            return R.error(ErrorTips.NO_SUCH_USER);
        }
        // 用户密码验证
        if (user.getPassword() == null || !user.getPassword().equals(password)) {
            return R.error(ErrorTips.ERROR_PWD);
        }

        // 用户信息验证成功
        // 来宾用户
        // 普通
        // 其他用户

        // 保存用户信息
        this.save(username, password, request, response);
        return R.success();
    }

    @PostMapping("/register")
    @ApiOperation("用户注册")
    public R register(@RequestBody User user) {
        return userService.register(user) ? R.success() : R.error(ErrorTips.UN_SAVE);
    }


    /**
     * 保存用户登录信息
     * @param username 用户名
     * @param password 密码
     * @param request 请求对象
     */
    public void save(String username, String password, HttpServletRequest request, HttpServletResponse response) {
        request.getSession().setAttribute(username, password);
    }


    /**
     * 验证用户合法性
     * @param username 用户名
     * @return 用户
     */
    public User userVerify(String username) {
        return userService.getUserInfo(username);
    }
}
